layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    let userId = JSON.parse(sessionStorage.getItem("userInfo")).id;
    $(function () {
        tableRender();
    })

    $("#find").click(function () {
        tableRender();
    });
    $("#clear").click(function () {
        $(".search_input").val("");
    })

    function tableRender() {
        table.render({
            elem: '#words_table'
            // , height: 312
            ,
            url: LOCALHOSTURL + '/words/words/getWords' //数据接口
            ,
            method: "get",
            where: {
                "userId": userId,
                "param": $("#param").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true //开启分页
            ,
            title: "单词表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'english',
                    title: '单词',
                    templet: function (res) {
                        if (res.english == null || res.english == '')
                            return '暂无';
                        else
                            return res.english;
                    }
                }, {
                    field: 'chinese',
                    title: '翻译',
                    templet: function (res) {
                        if (res.chinese == null || res.chinese == '')
                            return '暂无';
                        else
                            return res.chinese;
                    }
                }, {
                    field: 'author',
                    title: '作者',
                    templet: function (res) {
                        if (res.author != null && res.author != "")
                            return res.author;
                        else
                            return '暂无';
                    }
                }, {
                    field: 'createTime',
                    title: '发布时间',
                    templet: function (res) {
                        return res.createTime;
                    },
                    sort: true
                }, {
                    field: 'likesCount',
                    title: '点赞数',
                    templet: function (res) {
                        if (res.likesCount == null || res.likesCount == 0)
                            return 0;
                        else
                            return res.likesCount;
                    },
                    sort: true
                }, {
                    fixed: 'right',
                    title: '操作',
                    width: 120,
                    templet: function (res) {
                        let html = '';
                        if (res.isLike != null && res.isLike > 0)
                            html += '<a href="javascript:;" lay-event="like" id="like' + res.id + '"><span class="layui-anim layui-anim-scaleSpring"><i class="layui-icon layui-icon-heart-fill" title="取消点赞" style="font-size: 25px; color: hotpink"></i></span></a>';
                        else
                            html += '<a href="javascript:;" lay-event="like" id="like' + res.id + '"><span class="layui-anim layui-anim-scaleSpring"><i class="layui-icon layui-icon-heart" title="点赞" style="font-size: 25px; color: hotpink"></i></span></a>';
                        if (res.isCollect != null && res.isCollect > 0)
                            html += '<a href="javascript:;" lay-event="collect" id="collect' + res.id + '"><span class="layui-anim layui-anim-scaleSpring"><i class="layui-icon layui-icon-star-fill" title="取消收藏" style="font-size: 25px; color: yellow"></i></span></a>';
                        else
                            html += '<a href="javascript:;" lay-event="collect" id="collect' + res.id + '"><span class="layui-anim layui-anim-scaleSpring"><i class="layui-icon layui-icon-star" title="收藏" style="font-size: 25px; color: yellow"></i></span></a>';
                        return html;
                    }
                }
                ]
            ],
            done: function (res) {
                console.log(res);
            }
        });
    }

    table.on("toolbar(words_filter)", function (obj) {
        let data = obj.data
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 2,
                    title: "发布单词",
                    area: ['50%', '60%'],
                    content: ["editWords.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        // var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                        var iframeWin = layero.find('iframe')[0].contentWindow;
                        console.log(iframeWin);
                        iframeWin.editWord("",index);
                    }
                });
                break;
            case 'myWords':
                layer.open({
                    type: 2,
                    title: "我的单词",
                    area: ['100%', '100%'],
                    content: ["myWords.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    },
                    cancel: function () {
                        tableRender();
                    }
                });
                break;
            case 'myLikes':
                layer.open({
                    type: 2,
                    title: "我的喜欢",
                    area: ['100%', '100%'],
                    content: ["likeWords.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    },
                    cancel: function () {
                        tableRender();
                    }
                });
                break;
            case 'myCollects':
                layer.open({
                    type: 2,
                    title: "我的收藏",
                    area: ['100%', '100%'],
                    content: ["collectWords.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    },
                    cancel: function () {
                        tableRender();
                    }
                });
                break;
        }
    });
    table.on("tool(words_filter)", function (obj) {
        let data = obj.data;
        switch (obj.event) {
            case 'like':
                let likeData = {
                    "user": userId,
                    "word": data.id
                };
                let res = ajaxModel("/words/userLikes/updateUserLike", "post", likeData);
                if (res.code != 200)
                    layer.alert(res.message);
                else {
                    // tableRender();
                    if ($("#like" + data.id + " i").attr("class") == "layui-icon layui-icon-heart-fill") {
                        $("#like" + data.id + " i").attr("class", "layui-icon layui-icon-heart");
                        $("#like" + data.id + " i").attr("title", "点赞");
                    } else if ($("#like" + data.id + " i").attr("class") == "layui-icon layui-icon-heart") {
                        $("#like" + data.id + " i").attr("class", "layui-icon layui-icon-heart-fill");
                        $("#like" + data.id + " i").attr("title", "取消点赞")
                    }
                    table.render();
                }
                break;
            case 'collect':
                let collectData = {
                    "user": userId,
                    "word": data.id
                };
                let result = ajaxModel("/words/userCollect/updateUserCollect", "post", collectData);
                if (result.code != 200)
                    layer.alert(result.message);
                else {
                    // tableRender();
                    if ($("#collect" + data.id + " i").attr("class") == "layui-icon layui-icon-star-fill") {
                        $("#collect" + data.id + " i").attr("class", "layui-icon layui-icon-star");
                        $("#collect" + data.id + " i").attr("title", "收藏");
                    } else if ($("#collect" + data.id + " i").attr("class") == "layui-icon layui-icon-star") {
                        $("#collect" + data.id + " i").attr("class", "layui-icon layui-icon-star-fill");
                        $("#collect" + data.id + " i").attr("title", "取消收藏");
                    }
                    table.render();
                }
                break;
        }
    })
});